package com.github.hgkmail.hello.leetcode101.pointer.tree.order;

import com.github.hgkmail.hello.leetcode101.base.CommonUtil;
import com.github.hgkmail.hello.leetcode101.base.TreeNode;

import java.util.HashMap;
import java.util.Map;

public class LC105ConstructBinaryTreeFromPreorderAndInorderTraversal {
    //先序遍历，返回root本身
    //参数：4个坐标preorder左右边界，inorder左右边界
    //preorder用来确定[根节点及其坐标]，inorder用来确定[左右子树长度]
    public TreeNode dfs(int[] preorder, int[] inorder, Map<Integer, Integer> inorderMap,
                        int preLeft, int preRight, int inLeft, int inRight) {
        if (preLeft>preRight) {
            return null;
        }
        //根节点及其坐标
        int rootVal=preorder[preLeft];
        int rootInorderIndex=inorderMap.get(rootVal);
        TreeNode root = new TreeNode(rootVal);
        //左右子树的长度
        int subLeftLen=rootInorderIndex-inLeft;
        int subRightLen=inRight-rootInorderIndex;
        //计算坐标
        root.left=dfs(preorder, inorder, inorderMap,preLeft+1,preLeft+subLeftLen, inLeft, rootInorderIndex-1);
        root.right=dfs(preorder, inorder, inorderMap,preLeft+subLeftLen+1, preRight, rootInorderIndex+1, inRight);

        return root;
    }
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int len=preorder.length;
        if (len<=0) {
            return null;
        }
        Map<Integer, Integer> inorderMap = new HashMap<>();
        for (int i = 0; i < len; i++) {
            //inorderValue, inorderIndex
            inorderMap.put(inorder[i], i);
        }
        return dfs(preorder, inorder, inorderMap, 0, len-1, 0, len-1);
    }

    public static void main(String[] args) {
        TreeNode root=new LC105ConstructBinaryTreeFromPreorderAndInorderTraversal().buildTree(
                new int[]{3,9,20,15,7}, new int[]{9,3,15,20,7}
        );
        System.out.println(CommonUtil.serializeBinaryTree(root));
    }
}
